package com.le.core.login.Service.impl;

import com.google.protobuf.ServiceException;
import com.le.business.after.domin.UserIdentity;
import com.le.business.after.service.UserIdentityService;
import com.le.common.utils.SecurityUtils;
import com.le.core.login.Service.LoginService;
import com.le.core.login.domin.LoginUser;
import com.le.core.login.domin.PasswordLoginUser;
import com.le.core.web.service.TokenService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class PasswordLoginImpl implements LoginService<PasswordLoginUser> {

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserIdentityService userIdentityService;

    @Override
    public String login(PasswordLoginUser passwordLoginUser) throws ServiceException {

        String password = passwordLoginUser.getPassword();
        String userName = passwordLoginUser.getUserName();

        Authentication authentication = null;
        try {
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(userName, password));
        } catch (Exception e) {
            e.printStackTrace();
        }

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        return tokenService.createToken(loginUser);
    }

    @Override
    public boolean validateUser(PasswordLoginUser user) {

        return false;
    }

    @Override
    public String register(PasswordLoginUser user) {
        UserIdentity userIdentity = new UserIdentity();
        userIdentity.setClient(user.getClient());
        userIdentity.setCreateBy(user.getUserName());
        userIdentity.setCreateBy(user.getCreateTime());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return null;
    }
}
